#!/usr/bin/env python
# coding=utf-8

import os
import time
import urllib
import wsgiref.handlers
import hashlib

from google.appengine.api.labs import taskqueue
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.api import users

from auth import SECRET,ROOTSITE
from lock import CcdjhMarxHandler
from suki.cloud import Datum, Article, Category, Comment
from suki.cloud.purview import CheckAuth, DoAuth, CheckAuthSilence, DoAuthSilence

from suki.cloud.bot.sessions import Session
from suki.cloud.bot.cookies import Cookies

from django.core.paginator import ObjectPaginator, InvalidPage
from django.utils import simplejson


class OutdoorHandler(webapp.RequestHandler):
	def get(self):
		site_domain = Datum.get('site_domain')
		site_title = Datum.get('site_title')
		site_author = Datum.get('site_author')
		site_slogan = Datum.get('site_slogan')

		#articles = db.GqlQuery("SELECT * FROM Article WHERE is_page = False ORDER BY created DESC LIMIT 12")
		#pages = db.GqlQuery("SELECT * FROM Article WHERE is_page = TRUE AND is_for_sidebar = TRUE ORDER BY title ASC")
		category = db.GqlQuery("SELECT * FROM Category ORDER BY name ASC")
		template_values = {
			'site_domain' : site_domain[0],
			'site_title' : site_title[0],
			'site_author' : site_author[0],
			'site_slogan' : site_slogan[0],
		}
		output = memcache.get('index_output_a')
		if output is None:
			articles = memcache.get('index')
			if articles is None:
				articles = db.GqlQuery("SELECT * FROM Article WHERE is_page = False ORDER BY created DESC LIMIT 12")
				memcache.add("index", articles, 86400)
			pages = db.GqlQuery("SELECT * FROM Article WHERE is_page = TRUE AND is_for_sidebar = TRUE ORDER BY title ASC")
			template_values['articles'] = articles
			template_values['pages'] = pages
			template_values['category'] = category
			site_theme,ccdjh = Datum.get('site_theme')
			if site_theme is None:
				site_theme = 'default'
			themes = os.listdir(os.path.join(os.path.dirname(__file__), 'tpl', 'outdoor'))
			if site_theme not in themes:
				site_theme = 'default'
			path = os.path.join(os.path.dirname(__file__), 'tpl', 'outdoor', site_theme, 'default.html')
			output = template.render(path, template_values)
			memcache.set('index_output', output, 86400)
		self.response.out.write(output)

class OutdoorArchiveHandler(webapp.RequestHandler):
	def get(self):
		pass

class OutdooorAtomFeedHandler(webapp.RequestHandler):
	def get(self):
		site_title = Datum.get('site_title')
		site_slogan = Datum.get('site_slogan')
		site_author = Datum.get('site_author')
		site_email = Datum.get('site_email')
		site_domain = Datum.get('site_domain')
		site_updated_cc, list_cc = Datum.get('site_updated')
		if site_updated_cc is None:
			site_updated_cc = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
		template_values = {}
		template_values['site_title'] = site_title[0]
		template_values['site_slogan'] = site_slogan[0]
		template_values['site_author'] = site_author[0]
		template_values['site_email'] = site_email[0]
		template_values['site_domain'] = site_domain[0]
		output = memcache.get('feed_output')
		if output is None:
			articles = db.GqlQuery("SELECT * FROM Article WHERE is_page = False ORDER BY created DESC LIMIT 100")
			template_values['articles'] = articles
			template_values['articles_total'] = articles.count()
			template_values['site_updated'] = site_updated_cc
			path = os.path.join(os.path.dirname(__file__), 'tpl', 'shared', 'index.xml')
			output = template.render(path, template_values)
			memcache.set('feed_output', output, 86400)
		self.response.headers['Content-type'] = 'text/xml; charset=UTF-8'
		self.response.out.write(output)

class OutdoorAtomSitemapHandler(webapp.RequestHandler):
	def get(self):
		site_title = Datum.get('site_title')
		site_slogan = Datum.get('site_slogan')
		site_author = Datum.get('site_author')
		site_email = Datum.get('site_email')
		site_domain = Datum.get('site_domain')
		site_updated_cc, list_cc = Datum.get('site_updated')
		if site_updated_cc is None:
			site_updated_cc = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
		template_values = {}
		template_values['site_title'] = site_title[0]
		template_values['site_slogan'] = site_slogan[0]
		template_values['site_author'] = site_author[0]
		template_values['site_email'] = site_email[0]
		template_values['site_domain'] = site_domain[0]
		output = memcache.get('sitemap_output')
		if output is None:
			articles = db.GqlQuery("SELECT * FROM Article ORDER BY last_modified DESC")
			template_values['articles'] = articles
			template_values['articles_total'] = articles.count()
			template_values['site_updated'] = site_updated_cc
			path = os.path.join(os.path.dirname(__file__), 'tpl', 'shared', 'sitemap.xml')
			output = template.render(path, template_values)
			memcache.set('sitemap_output', output, 86400)
		self.response.headers['Content-type'] = 'text/xml; charset=UTF-8'
		self.response.out.write(output)


class OutdoorRobotsHandler(webapp.RequestHandler):
	def get(self):
		template_values = {}
		path = os.path.join(os.path.dirname(__file__), 'tpl', 'shared', 'robots.txt')
		self.response.headers['Content-type'] = 'text/plain; charset=UTF-8'
		self.response.out.write(template.render(path, template_values))

class OutdoorArticleHandler(webapp.RequestHandler):
	def get(self, url):
		site_domain = Datum.get('site_domain')
		site_title = Datum.get('site_title')
		site_author = Datum.get('site_author')
		site_slogan = Datum.get('site_slogan')
		self.session = Session()
		article = db.GqlQuery("SELECT * FROM Article WHERE title_url = :1 LIMIT 1", url)
		pages = db.GqlQuery("SELECT * FROM Article WHERE is_page = TRUE AND is_for_sidebar = TRUE ORDER BY title ASC")
		category_all = db.GqlQuery("SELECT * FROM Category ORDER BY name ASC")
		if (article.count() == 1):
			article_found = True
			article = article[0]
			article.hits = article.hits + 1
			try:
				article.put()
			except:
				article.hits = article.hits - 1
			comments = db.GqlQuery("SELECT * FROM Comment WHERE comment_parent_url = :1 ", url)
			if 'commentmessage' in self.session:
				message = self.session['commentmessage']
				if 'commentmessage_email' in self.session:
					message_email = self.session['commentmessage_email']
				else:
					message_email = 'robot'
				cookies = Cookies(self, max_age = 86400, path = '/')
				if 'commentlogin' in cookies:
					comment_form = 'True'
				else:
					comment_form = None
			else:
				message = 'Guest'
				message_email = 'robot'
				comment_form = None
			template_values = {}
			
			template_values['site_domain'] = site_domain[0]
			template_values['site_title'] = site_title[0]
			template_values['site_author'] = site_author[0]
			template_values['site_slogan'] = site_slogan[0]
			
			template_values['article_page'] = article
			template_values['pages'] = pages
			template_values['category'] = category_all
			template_values['comments'] = comments
			template_values['message'] = message
			template_values['message_email'] = message_email
			template_values['comment_form'] = comment_form
			site_theme,ccdjh = Datum.get('site_theme')
			if site_theme is None:
				site_theme = 'default'
			themes = os.listdir(os.path.join(os.path.dirname(__file__), 'tpl', 'outdoor'))
			if site_theme not in themes:
				site_theme = 'default'
			path = os.path.join(os.path.dirname(__file__), 'tpl', 'outdoor', site_theme, 'article.html')
			output = template.render(path, template_values)
			self.response.out.write(output)
		else:
			category = db.GqlQuery("SELECT * FROM Category WHERE category_url = :1 ", url)
			if (category.count() == 1):
				article_found = True
				category = category[0]
				category_article =category.categoryall()
				template_values = {}
				
				template_values['site_domain'] = site_domain[0]
				template_values['site_title'] = site_title[0]
				template_values['site_author'] = site_author[0]
				template_values['site_slogan'] = site_slogan[0]
				
				template_values['category_article'] = category_article
				template_values['pages'] = pages
				template_values['category'] = category_all
			else:
				template_values = {}
				nofind = "404 not find"
				
				template_values['site_domain'] = site_domain[0]
				template_values['site_title'] = site_title[0]
				template_values['site_author'] = site_author[0]
				template_values['site_slogan'] = site_slogan[0]
				
				template_values['article'] = article
				template_values['pages'] = pages
				template_values['category'] = category_all
				template_values['nofind'] = nofind
			site_theme,ccdjh = Datum.get('site_theme')
			if site_theme is None:
				site_theme = 'default'
			themes = os.listdir(os.path.join(os.path.dirname(__file__), 'tpl', 'outdoor'))
			if site_theme not in themes:
				site_theme = 'default'
			path = os.path.join(os.path.dirname(__file__), 'tpl', 'outdoor', site_theme, 'category.html')
			output = template.render(path, template_values)
			self.response.out.write(output)
 
def main():
	application = webapp.WSGIApplication([
	('/', OutdoorHandler),
	('/archive', OutdoorArchiveHandler),
	('/index.xml', OutdooorAtomFeedHandler),
	('/sitemap.xml', OutdoorAtomSitemapHandler),
	('/robots.txt', OutdoorRobotsHandler),
	('/([0-9a-zA-Z\-\.]+)', OutdoorArticleHandler)
	],
										debug=True)
	wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
